package com.xiake.zojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.xiake.zojcodesandbox.enums.ExecuteStatusEnum;
import com.xiake.zojcodesandbox.model.ExecuteCodeRequest;
import com.xiake.zojcodesandbox.model.ExecuteCodeResponse;
import com.xiake.zojcodesandbox.model.ExecuteMessage;
import com.xiake.zojcodesandbox.model.JudgeInfo;
import com.xiake.zojcodesandbox.utils.ProcessUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JavaNativeCodeSandboxOld implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long Max_Execute_Time = 5000;
    private static final long Max_Memory = 256;
    private static final String Max_Memory_Param = "-Xmx" + Max_Memory + "m";
    private static final WordTree wordTree=new WordTree();

    static {
        wordTree.addWord("exec");
        wordTree.addWord("execute");
        wordTree.addWord("File");
    };


    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaNativeCodeSandbox = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafeCode/WriteFileError.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    public  ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest){
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //判断输入的代码是否包含敏感恶意命令
        if(wordTree.isMatch(code)){
            System.out.println(wordTree.match(code));
            return ExecuteCodeResponse.builder().message("代码包含敏感命令").build();
        }

        //1.把用户的代码保存为文件
        //"user.dir" 是Java系统属性中的一个键。这个属性表示Java应用程序的“用户工作目录”的路径。
        String userDir = System.getProperty("user.dir");  //获取当前工作目录
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断文件夹是否存在
        if(!FileUtil.exist(globalCodePathName)){
            //不存在则创建
            FileUtil.mkdir(globalCodePathName);
        }
        //每次生成的目录都是不同的，用户代码隔离
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        //读取用户的代码内容写到指定的Main.java文件中
        File userCodeFile=FileUtil.writeString(code, userCodePath, "utf-8");


        //2.编译文件
        //编译命令：javac Main.java
        String compileCmd=String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        System.out.println(userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            getErrorResponse(e);
        }

        //3.执行文件
        ArrayList<ExecuteMessage>  executeMessageList= new ArrayList<>();
        for(String input:inputList) {
            //执行命令：java Main 1 2
            String executeCmd = String.format("java %s -Dfile.encoding=UTF-8 -cp %s Main %s",Max_Memory_Param, userCodeParentPath,input);
            try {
                Process runProcess = Runtime.getRuntime().exec(executeCmd);

                //设置守护线程，当主线程执行时间超过设置的最大执行时间，就销毁主线程
                //防止主线程一直占用资源
                //todo 待优化
                new Thread(() -> {
                    try {
                        Thread.sleep(Max_Execute_Time);
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();

            //返回执行信息
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "执行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);

            } catch (Exception e) {
//                throw new RuntimeException(e);
                getErrorResponse(e);
            }
        }

        //4.整理输出结果
        long maxTime=0;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        //将executeMessageList中的每一个ExecuteMessage对象转换为其getMessage方法的返回值，并将这些返回值收集到一个新的列表中。
        List<String> outPutMeassageList =new ArrayList<>();
        //对执行信息列表进行遍历，将每个执行信息对象中的message属性值取出来，并放入到新的列表中。
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(executeMessage.getErrorMessage())){
                //如果执行信息对象中的errorMessage属性值不为空，则说明执行失败了
                //用户提交的代码错误
                executeCodeResponse.setMessage(ExecuteStatusEnum.USER_CODE_ERROR.getMessage());
                executeCodeResponse.setStatus(ExecuteStatusEnum.USER_CODE_ERROR.getStatus());
                break;
            }
            outPutMeassageList.add(executeMessage.getMessage());
            //找出最大执行时间
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        executeCodeResponse.setOutputList(outPutMeassageList);
        if(executeMessageList.size()==outPutMeassageList.size()){
            //如果执行信息列表和输出结果列表的长度相同，说明每一条都执行成功，则设置状态为1
            executeCodeResponse.setStatus(ExecuteStatusEnum.SUCCESS.getStatus());
        }
        //设置JudgeInfo对象
        JudgeInfo judgeInfo = new JudgeInfo();
        // 取用时最大值，便于判断是否超时

        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();

        executeCodeResponse.setJudgeInfo(judgeInfo);


        //5.删除用户代码目录
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }

        return  executeCodeResponse;
    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getStatus());
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
